<template>
  <IModal
    :show="show"
    title="编辑"
    @after-enter="afterEnter"
    @after-leave="afterLeave"
    @close="close"
  >
    <IFormModal :modal="form" :rules="rules" ref="iref">
      <!-- <n-form label-width="auto" label-placement="left" ref="formRef" :model="form" :rules="rules"> -->
      <n-form-item label="编码" path="code" show-require-mark>
        <n-input v-model:value="form.code" :disabled="!isIns" />
      </n-form-item>
      <n-form-item label="名称" path="name" show-require-mark>
        <n-input v-model:value="form.name" />
      </n-form-item>
      <n-form-item label="值" path="value" show-require-mark>
        <n-input v-model:value="form.value" />
      </n-form-item>
      <n-form-item label="状态" path="status" show-require-mark>
        <n-radio-group v-model:value="form.status">
          <n-radio
            :label="item.label"
            :value="item.value"
            :key="item.value"
            v-for="item in codeStore.getCodesByDict(_Dict.Status)"
          />
        </n-radio-group>
      </n-form-item>
      <n-form-item label="备注">
        <n-input type="textarea" v-model:value="form.remark" />
      </n-form-item>
      <!-- </n-form> -->
    </IFormModal>
    <template #footer>
      <n-button @click="close">关闭</n-button>
      <n-button type="info" @click="handleConfirmOnClick">确认</n-button>
    </template>
  </IModal>
</template>
<script lang="ts" setup>
import { getParam, postOrPutParam } from '@/api/system/Param'
import IModal from '@/views/components/IModal/IModal.vue'
import IFormModal from '@/views/components/IModal/IFormModal.vue'

const codeStore = useCodeStore()

const props: IFormProps<SystemParamPO> = defineProps({
  show: {
    type: Boolean
  },
  po: {
    type: Object as PropType<SystemParamPO>,
    required: true
  }
})

const emits = defineEmits<{
  (e: 'handleCloseOnClick'): void
  (e: 'handleSelectOnClick'): void
}>()

const state = reactive<IFormState<SystemParamPO>>({
  isIns: true,
  form: {} as SystemParamPO
})

const { isIns, form } = toRefs(state)

const iref = ref()

const rules: FormRules = {
  code: [
    {
      required: true
    }
  ],
  name: [
    {
      required: true
    }
  ],
  value: [
    {
      required: true
    }
  ],
  status: [
    {
      required: true
    }
  ]
}

const afterEnter = async () => {
  state.isIns = Object.keys(props.po).length == 0
  console.info(state.isIns)
  if (state.isIns) return
  const { data } = await getParam(props.po.id)
  state.form = data
}

const handleConfirmOnClick = async () => {
  iref.value?.formRef.validate(async (errors: any) => {
    if (errors) return
    await postOrPutParam(state.form)
    select()
    close()
  })
}

const select = () => {
  emits('handleSelectOnClick')
}

const close = () => {
  emits('handleCloseOnClick')
}

const afterLeave = () => {
  handleReset(state.form)
}
</script>
